<?php
/**
 * Created by PhpStorm.
 * User: Powerless
 * Date: 2017-7-17
 * Time: 16:15
 * Content: 人有悲欢离合，Bug有阴晴圆缺
 */

namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;
use think\Validate;


class GiftController extends AdminbaseController
{
    public function index()
    {
        $param    = $this->request->param();
        $g_name = isset($param['g_name']) ? $param['g_name'] : '';
        $where = null;
        if($g_name){ $where['g_name'] = ['like', "%$g_name%"];}else{ unset($param['g_name']);}
        $shout = Db::name('gift_list')->where($where)->order(["g_status" => "ASC","id" => "DESC"])->paginate(20);
        $shout->appends($param);
        $page = $shout->render();
        $this->assign("g_name", $g_name);
        $this->assign("shout", $shout);
        $this->assign("page", $page);
        return $this->fetch();
    }

    public function stars()
    {
        $param    = $this->request->param();
        $s_name = isset($param['s_name']) ? $param['s_name'] : '';
        $where = null;
        if($s_name){ $where['s_name'] = ['like', "%$s_name%"];}else{ unset($param['s_name']);}
        $star = Db::name('star_list')->where($where)->order(['id' => 'DESC'])->paginate(5);
        $star->appends($param);
        $page = $star->render();
        $this->assign("s_name", $s_name);
        $this->assign("star", $star);
        $this->assign("page", $page);
        return $this->fetch();
    }

    public function annal()
    {
        $param    = $this->request->param();
        $s_name = isset($param['s_name']) ? $param['s_name'] : '';
        $where['gs.g_glid'] = $param['id'];
        if($s_name){ $where['sl.s_name'] = ['like', "%$s_name%"];}else{ unset($param['s_name']);}
        $gift = Db::name('gift_star')
            ->field('gs.id,sl.s_name,gs.g_amount,gs.g_use,gs.g_createtime,gs.g_lasttime,gs.g_description')
            ->alias('gs')
            ->join('star_list sl','gs.g_udid = sl.s_udid')
            ->where($where)
            ->order(['gs.id' => 'DESC'])
            ->paginate(20);
        $gift->appends($param);
        $page = $gift->render();
        $this->assign("s_name", $s_name);
        $this->assign("glid", $param['id']);
        $this->assign("gift", $gift);
        $this->assign("page", $page);
        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function addPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'g_name' => 'require|chsAlphaNum|min:4|max:32',
                'g_sponsor' => 'require|chsAlpha|min:2|max:16',
                'g_password' => 'require|number|between:100000,999999|unique:gift_list,g_password',
                'g_phone' => 'require|number|min:8|max:16',
                'g_url' => 'require|min:8|max:64',
                'g_total' => 'require|number|between:1,100000',
                'g_validtime' => 'require|dateFormat:Y-m-d H:i|after:+7 day|before:+1 year',
                'g_status' => 'require|number',
            ]);
            $validate->message([
                'g_name.require' => '礼物名称不可为空',
                'g_name.chsAlpha' => '礼物名称只能是只能是汉字、字母和数字',
                'g_name.min' => '礼物名称最小长度为4个汉字或字母',
                'g_name.max' => '礼物名称最大长度为32个汉字或字母',
                'g_sponsor.require' => '赞助商名称不可为空',
                'g_sponsor.chsAlpha' => '赞助商名称只能是汉字或字母',
                'g_sponsor.min' => '赞助商名称最小长度为2个汉字或字母',
                'g_sponsor.max' => '赞助商名称最大长度为16个汉字或字母',
                'g_password.require' => '兑换密码不可为空',
                'g_password.number' => '兑换密码只能是数字',
                'g_password.between' => '兑换密码只能在100000~999999之间',
                'g_password.unique' => '兑换密码已存在',
                'g_phone.require' => '联系电话不可为空',
                'g_phone.number' => '联系电话只能是数字',
                'g_phone.min' => '联系电话最小长度为8个数字',
                'g_phone.max' => '联系电话最大长度为16个数字',
                'g_url.require' => '兑换网址不可为空',
                'g_url.min' => '兑换网址最小长度为8个字母',
                'g_url.max' => '兑换网址最大长度为64个字母',
                'g_total.require' => '礼品总数不可为空',
                'g_total.number' => '礼品总数只能是数字',
                'g_total.between' => '礼品总数只能在1~100000之间',
                'g_validtime.require' => '有效期不能为空',
                'g_validtime.dateFormat' => '有效期格式不正确',
                'g_validtime.after' => '有效期时间过短',
                'g_validtime.before' => '有效期时间过长',
                'g_status.require' => '请选择礼品状态',
                'g_status.number' => '礼品状态不正确',
            ]);
            $data = $this->request->post();
            if ($validate->check($data)) {
                $data['g_userid'] = cmf_get_current_admin_id();
                Db::name('gift_list')->insert($data);
                $this->success('添加成功','gift/index');
            }else{
                $this->error($validate->getError());
            }
        }else{
            $this->error('请求错误');
        }
    }

    public function edit()
    {
        $id    = $this->request->param('id', 0, 'intval');
        $gift = DB::name('gift_list')->where(["id" => $id])->find();
        $this->assign("gift", $gift);
        return $this->fetch();
    }

    public function editPost()
    {        if ($this->request->isPost()) {
        $validate = new Validate([
            'g_name' => 'require|chsAlphaNum|min:4|max:32',
            'g_sponsor' => 'require|chsAlpha|min:2|max:16',
            'g_password' => 'require|number|between:100000,999999',
            'g_phone' => 'require|number|min:8|max:16',
            'g_url' => 'require|min:8|max:64',
            'g_validtime' => 'require|dateFormat:Y-m-d H:i|after:+7 day|before:+1 year',
            'g_status' => 'number',
            'add' => 'number|between:0,10000',
        ]);
        $validate->message([
            'g_name.require' => '礼物名称不可为空',
            'g_name.chsAlpha' => '礼物名称只能是只能是汉字、字母和数字',
            'g_name.min' => '礼物名称最小长度为4个汉字或字母',
            'g_name.max' => '礼物名称最大长度为32个汉字或字母',
            'g_sponsor.require' => '赞助商名称不可为空',
            'g_sponsor.chsAlpha' => '赞助商名称只能是汉字或字母',
            'g_sponsor.min' => '赞助商名称最小长度为2个汉字或字母',
            'g_sponsor.max' => '赞助商名称最大长度为16个汉字或字母',
            'g_password.require' => '兑换密码不可为空',
            'g_password.number' => '兑换密码只能是数字',
            'g_password.between' => '兑换密码只能在100000~999999之间',
            'g_phone.require' => '联系电话不可为空',
            'g_phone.number' => '联系电话只能是数字',
            'g_phone.min' => '联系电话最小长度为8个数字',
            'g_phone.max' => '联系电话最大长度为16个数字',
            'g_url.require' => '兑换网址不可为空',
            'g_url.min' => '兑换网址最小长度为8个字母',
            'g_url.max' => '兑换网址最大长度为64个字母',
            'g_validtime.require' => '有效期不能为空',
            'g_validtime.dateFormat' => '有效期格式不正确',
            'g_validtime.after' => '有效期时间过短',
            'g_validtime.before' => '有效期时间过长',
            'g_status.number' => '请选择礼品状态',
            'add.number' => '新增礼品只能是数字',
            'add.between' => '新增礼品只能在0~10000之间',
        ]);
        $data = $this->request->post();
        if ($validate->check($data)) {
            if($data['add']){
                Db::name('gift_list')->where(['id'=>$data['id']])->setInc('g_total',$data['add']);
            }
            unset($data['add']);
            Db::name('gift_list')->update($data);
            $this->success('修改成功','gift/index');
        }else{
            $this->error($validate->getError());
        }
    }else{
        $this->error('请求错误');
    }
    }

    public function issued()
    {
        $id    = $this->request->param('id', 0, 'intval');
        $gift = DB::name('gift_list')->where(["id" => $id])->find();
        $this->assign("gift", $gift);
        $this->assign("glid", $id);
        return $this->fetch();
    }

    public function issuedPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'g_udid' => 'require|number',
                'g_glid' => 'require|number',
                'g_amount' => 'require|number|between:1,1000',
                'g_description' => 'chsDash|max:64',
            ]);
            $validate->message([
                'g_udid.require' => '请选择用户',
                'g_udid.number' => '所选用户ID错误',
                'g_glid.require' => '请选择礼品',
                'g_glid.number' => '所选礼品ID错误',
                'g_amount.require' => '请填写下发数量',
                'g_amount.number' => '下发数量只能是数字',
                'g_amount.between' => '下发数量只能在1~1000之间',
                'g_amount.compare' => '下发数量必须小于等于可用数量',
                'g_description.chsDash' => '联系电话只能是数字',
                'g_description.max' => '联系电话最大长度为64个数字',
            ]);
            $data = $this->request->post();
            if ($validate->check($data)) {
                $where['id'] = $data['g_glid'];
                $where['g_total - g_use - '.$data['g_amount']] = ['egt',0];
                if(!Db::name('gift_list')->where($where)->find()){
                    $this->error('礼品库存不足');
                }
                $data['g_userid'] = cmf_get_current_admin_id();
                Db::name('gift_list')->where(['id'=>$data['g_glid']])->setInc('g_use',$data['g_amount']);
                Db::name('gift_star')->insert($data);
                $this->createCard($data['g_udid'],$data['g_glid'],$data['g_amount']);
                $this->success('下发成功','gift/index');
            }else{
                $this->error($validate->getError());
            }
        }else{
            $this->error('请求错误');
        }
    }


    public function enabled()
    {
        $id    = $this->request->param('id', 0, 'intval');
        $shout = DB::name('gift_list')->where(["id" => $id])->find();
        switch ($shout['g_status']){
            case 10:
                DB::name('gift_list')->where(["id" => $id])->setField('g_status', 20);
                $this->success('您已停用此礼品');
                break;
            case 20:
                DB::name('gift_list')->where(["id" => $id])->setField('g_status', 10);
                $this->success('您已启用此礼品');
                break;
            default:
                DB::name('gift_list')->where(["id" => $id])->setField('g_status', 20);
                $this->error('未知的礼品状态,已置为停用');
        }
    }

    private function createCard($udid,$glid,$amount)
    {
        //设置每次创建数量
        $bout = 32;
        //计算最小循环次数、向下取整
        $num = floor($amount/$bout);
        if($num){
            for($i=0;$i<$num;$i++){
                $this->cycle($udid,$glid,$bout);
            }
            //计算不足创建数据量的数量的剩余次数
            $surplus = $amount - $bout * $num;
            $this->cycle($udid,$glid,$surplus);
        }else{
            $this->cycle($udid,$glid,$amount);
        }
    }

    private function cycle($udid,$glid,$amount)
    {
        $data = null;
        for($i=0;$i<$amount;$i++){
            $card = sprintf('%04d%04d%03d', mt_rand(0, 9999), mt_rand(0, 9999), mt_rand(0, 999));
            $data[$i]['g_udid'] = $udid;
            $data[$i]['g_glid'] = $glid;
            $data[$i]['g_number'] = $card.$this->calcIDCardCode($card);
        }
        Db::name('gift_card')->insertAll($data);
    }

    //计算最后一位验证码,根据国家标准GB 11643-1999
    private function calcIDCardCode($IDCardBody)
    {
        if (strlen($IDCardBody) != 11) {
            return false;
        }
        //加权因子
        $factor = array(4 ,5, 3, 8, 2, 1, 6, 7, 9, 5, 8);
        //校验码对应值
        $code = array('1', '0', '9', '8', '7', '6', '5', '4', '3', '2');
        $checksum = 0;
        for ($i = 0; $i < strlen($IDCardBody); $i++) {
            $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
        }
        return $code[$checksum % 10];
    }
}